<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { FormInstance } from 'element-plus';
import { ApiConfigForm, HttpMethod } from '../../../utils/types';
import { createNonEmptyRule, createRequiredRule, throwError, treeUtil } from '../../../utils';
import { apiDict } from '../../../api';
import { IStepForm, useConfig  } from '../utils';
import UiParamConfig from './ParamConfig.vue';

const cls = 'ui-api-editor-request'

const props = defineProps<{ modelValue: ApiConfigForm }>()

const emit = defineEmits(['update:modelValue'])

const updateModel = (v: ApiConfigForm) => emit('update:modelValue', v)

const { isPutOrPost, isTree } = useConfig(props)

const httpMethods = ref([])
const contentTypes = ref([])
const authTypes = ref([])

const formRef = ref<FormInstance>()

const rules = {
  name: createNonEmptyRule('请输入API名称'),
  method: createRequiredRule('请选择请求方式'),
  requestType: createRequiredRule('请选择请求类型'),
  authenrization: createRequiredRule('请选择认证方式')
}

const onMethodChange = (v: any) => {
  if (![HttpMethod.POST, HttpMethod.PUT].includes(v)) {
    updateModel({
      ...props.modelValue,
      requestBody: [],
      requestType: undefined
    })
  }
}

const onContentTypeChange = () => {
  updateModel({ ...props.modelValue, requestBody: [] })
}

onMounted(() => {
  apiDict
    .getList(apiDict.DictType.HTTP_METHOD)
    .then(res => {
      httpMethods.value = res.rows
    })
  apiDict
    .getList(apiDict.DictType.CONTENT_TYPE)
    .then(res => {
      contentTypes.value = res.rows
    })
  apiDict
  .getList(apiDict.DictType.AUTH_TYPE)
  .then(res => {
    authTypes.value = res.rows
  })
})

const validate = async () => {
  await formRef.value.validate()
  const row = treeUtil.find({
    data: [
      ...props.modelValue.requestHeader,
      ...props.modelValue.requestParam,
      ...props.modelValue.requestPath,
      ...props.modelValue.requestBody
    ],
    callback: node => !node.param || (!node.paramType&&node.paramType!=0)
  })
  if (row) {
    return throwError('请完善入参定义')
  }
}

defineExpose<IStepForm>({
  getForm: () => props.modelValue.value,
  validate
})
</script>

<template>
  <div :class="cls">
    <ElForm ref="formRef" label-width="8em" label-suffix=" :" :model="props.modelValue" :rules="rules">
      <ElFormItem label="API名称" prop="name" style="max-width: 410px;">
        <ElInput v-model="props.modelValue.name" placeholder="请输入API名称" />
      </ElFormItem>
      <ElFormItem label="认证方式" prop="authenrization">
        <ElRadioGroup v-model="props.modelValue.authenrization">
          <ElRadio v-for="_ in authTypes" :key="_.dictValue" :label="_.dictValue" >{{ _.dictLabel }}</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem label="协议">HTTP/HTTPS</ElFormItem>
      <ElFormItem label="请求方式" prop="method">
        <ElRadioGroup v-model="props.modelValue.method" @change="onMethodChange">
          <ElRadio v-for="_ in httpMethods" :key="_.dictValue" :label="_.dictValue" />
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem v-if="isPutOrPost" label="请求类型" prop="requestType">
        <ElRadioGroup v-model="props.modelValue.requestType" @change="onContentTypeChange">
          <ElRadio v-for="_ in contentTypes" :key="_.dictValue" :label="_.dictValue" />
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem :class="`${cls}_params`" label="入参定义">
        <ElTabs>
          <ElTabPane label="Header">
            <UiParamConfig v-model="props.modelValue.requestHeader" />
          </ElTabPane>
          <ElTabPane label="Param">
            <UiParamConfig v-model="props.modelValue.requestParam" />
          </ElTabPane>
          <ElTabPane label="Path">
            <UiParamConfig v-model="props.modelValue.requestPath" />
          </ElTabPane>
          <ElTabPane v-if="isPutOrPost" label="Body">
            <UiParamConfig :isTree="isTree" v-model="props.modelValue.requestBody" />
          </ElTabPane>
        </ElTabs>
      </ElFormItem>
    </ElForm>
  </div>
</template>

<style lang="scss">
.ui-api-editor-request {
  &_params {
    flex-wrap: wrap;
    .el-form-item__content {
      flex: auto;
      width: 100%;
      padding: 0 $page-padding;
      margin-top: 10px;
    }
    .el-tabs {
      width: 100%;
    }
    .cell {
      padding: 0 6px;
      display: flex;
      align-items: center;
    }
  }
  &_actions {
    width: 100%;
    margin-top: $page-padding;
    text-align: center;
  }
}
</style>
